package com.github.xzb617.client.flow.core.rules.rule;

import com.github.xzb617.client.flow.cache.CounterCache;
import com.github.xzb617.client.flow.constant.CacheKey;
import com.github.xzb617.client.flow.core.FlowContext;
import com.github.xzb617.client.flow.core.FlowException;
import com.github.xzb617.client.flow.core.FlowProperties;
import com.github.xzb617.client.flow.core.rules.chain.Rule;
import com.github.xzb617.client.flow.core.rules.chain.RuleChain;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class IpRule implements Rule {

    @Override
    public void validateInternal(FlowContext context, FlowProperties.RulesProperties config, CounterCache cache, RuleChain chain) throws FlowException {
        // 获取配置
        Map<String, Integer> limits = config.getLimits().get("IP");
        String ip = context.getIp();
        if (limits!=null && limits.containsKey(ip)) {
            long rate = limits.get(ip);
            // 从缓存中加载全局速率
            long ipRateFromCache = cache.incrementAndGet(getCacheKey(ip));
            if (ipRateFromCache > rate) {
                throw new FlowException("Too Many Request");
            }
        }
    }

    private String getCacheKey(String ip) {
        return CacheKey.FLOW + ":rules:ip:" + ip;
    }

}
